#include <signal.h>
#include <iostream>

#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/HttpUtil.h>
#include <workflow/HttpMessage.h>

using std::cout;
using std::endl;
using std::string;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    cout << "sighandler is processing" << endl;
    waitGroup.done();
}

//当调用回调函数时，请求和响应已经都已经被框架获取到了
//接下来就是对数据进行处理的过程
void httpCallback(WFHttpTask * httpTask)
{
    cout << "httpCallback is running" << endl;
    //检查错误情况
    auto req = httpTask->get_req();
    auto resp = httpTask->get_resp();
    int state = httpTask->get_state();
    int error = httpTask->get_error();
    switch(state){
    case  WFT_STATE_SYS_ERROR:
        printf("system error: %s\n", strerror(error));break;
    case  WFT_STATE_DNS_ERROR:
        printf("dns error: %s", gai_strerror(state)); break;
    case WFT_STATE_SUCCESS:
        break;
    }
    if(state != WFT_STATE_SUCCESS) {
        printf("occurs error\n");
        return;
    }

    //解析请求的信息
    //起始行
    printf("%s %s %s\n", req->get_method(),
           req->get_request_uri(),
           req->get_http_version());
    //首部字段
    protocol::HttpHeaderCursor cursor(req);
    string key, value;
    while(cursor.next(key, value)) {
        cout << key << ":" << value << endl;
    }
    cout << endl;
    
    //解析响应的信息
    //起始行
    printf("%s %s %s\n", resp->get_http_version(),
           resp->get_status_code(),
           resp->get_reason_phrase());

    //首部字段
    protocol::HttpHeaderCursor cursor2(resp);
    while(cursor2.next(key, value)){
        cout << key << ":" << value << endl;
    }

    //解析报文体
    const void * body = nullptr;
    size_t size = 0;
    resp->get_parsed_body(&body, &size);
    printf("%s\n", (char*)body);
    
}

void test0()
{
    signal(SIGINT, sighandler);

    //1. 创建HTTP的任务
    auto httpTask = WFTaskFactory::create_http_task(
                    "http://localhost", 0, 0, httpCallback);

    //2. 设置任务的属性
    auto req = httpTask->get_req();
    req->add_header_pair("User-Agent", "workflow http client");
    req->add_header_pair("Accept", "*/*");

    //3. 交给框架去调度执行
    httpTask->start();//异步运行
    waitGroup.wait();//调用它就会阻塞进程
}


int main()
{
    test0();
    return 0;
}

